package com.quark.data.type;

import java.text.ParseException;
import java.util.Date;

import com.quark.framework.utility.QuarkLog;
import com.quark.framework.utility.QuarkUtilDateHelper;

public class QuarkVariable {

	private Object value = null;
	private Class<?> defaultType = null;
	public QuarkVariable(Object val, Class<?> type)
	{
		value = val;
		defaultType = type;
	}
	
	public QuarkVariable()
	{
		
	}
	
	public Integer toInteger()
	{
		if(value == null)
			return null;
		
		if(value.getClass().equals(Integer.class))
		{
			return (Integer)value;
		}
		else if(value.getClass().equals(String.class))
		{
			try
			{
				return (Integer.valueOf(value.toString()));
			}
			catch(Exception e) 
			{
				QuarkLog.logError("QuarkVariable: can't parse from String '" + value.toString() + "' to Integer");
				return null;
			}
		}		
		else
		{
			QuarkLog.log("QuarkVariable: can't parse from" + value.getClass().getName() + " to " + Integer.class.getName());
			return null;
		}
	}
	
	public String toString()
	{
		if(value == null)
			return null;
		if(value.getClass().equals(Date.class))
		{
			return QuarkUtilDateHelper.getDateString((Date)value);
		}
		return value.toString();
	}
	
	public Date toDate()
	{
		if(value == null)
			return null;
		
		if(value.getClass().equals(Date.class))
		{
			return (Date)value;
		}
		else if(value.getClass().equals(String.class))
		{
			try {
				return QuarkUtilDateHelper.parseDate(value.toString());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				QuarkLog.log(e);
				return null;
			}
		}
		return null;
	}
	
	public Object getRawObject()
	{
		return value;
	}
	
	public void setRawObject(Object val, Class<?> type)
	{
		value = val;
		defaultType = type;
	}
	
	public void setDefaultType(Class<?> type)
	{
		defaultType = type;
	}
	
	public Class<?> getDefaultTypeClass()
	{
		return defaultType;
	}
	
	public Object toDefault()
	{
		if(defaultType == null)
		{
			QuarkLog.logError(getClass().getName(), "can't parse default, default type null");
			return null;
		}
		if(defaultType.equals(String.class))
			return toString();
		else if(defaultType.equals(Integer.class))
			return toInteger();
		else if(defaultType.equals(Date.class))
			return toDate();
		else
			return null;
	}
}
